import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServer {
    private DatagramSocket socket=null;
    public UdpServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    public void start() throws IOException {
        while(true){
            //1.receive datagram
            DatagramPacket requestPacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);

            //2.process
            String request =new String(requestPacket.getData(),0, requestPacket.getLength());
            String response="pong";

            //3.send response
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes()
                    .length,requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //4. print log
            System.out.printf("[%s:%d] req:%s,resp:%s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);


        }
    }


    public static void main(String[] args) throws IOException {
        UdpServer server=new UdpServer(12521);
        server.start();
    }
}
